package com.larry.juc;

import lombok.Getter;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ProjectName JUC
 * @Author larry
 * @Date 15:47 2021/7/13
 * @Description TODO
 **/
public class CompletableFutureNetMallDemo {
    static List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("tb"),
            new NetMall("pdd"),
            new NetMall("ddw"),
            new NetMall("tm")
    );


    //同步
    public static List<String> getPriceByStep(List<NetMall> list,String productName){
        return list.stream().map(netMall -> String.format(productName + " in %s price is %.2f",netMall.getProductName(),netMall.calcPrice(productName))).collect(Collectors.toList());
    }

    //异步
    public static List<String> getPriceByAsync(List<NetMall> list,String productName){
        return list.stream().map(netMall -> CompletableFuture.supplyAsync(() -> String.format(productName + " in %s price is %.2f",netMall.getProductName(),netMall.calcPrice(productName)))).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList());
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        List<String> java = getPriceByStep(list, "java");
        for (String element : java) {
            System.out.println(element);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("---耗时--- " + (endTime - startTime) + " ms");

        long startTime2 = System.currentTimeMillis();
        List<String> java2 = getPriceByAsync(list, "java");
        for (String element : java2) {
            System.out.println(element);
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("---耗时--- " + (endTime2 - startTime2) + " ms");
    }
}

class NetMall{

    @Getter
    private String productName;

    public NetMall(String productName) {
        this.productName = productName;
    }
    public double calcPrice(String productName){
        try { TimeUnit.SECONDS.sleep(1); }catch (InterruptedException e){ e.printStackTrace(); }

        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}
